<template>
  <Modal v-model="setModal" :title="title" width="1020">
    <div style="color: #ff0000; margin-bottom: 10px;">提示：直接输入数字，支持两位小数。如5.5%，输入5.5即可。一级分销商返佣比例<span style="font-weight: bold;"> 小于 </span>二级分销商返佣比例</div>
    <div>
      <div>提货点返佣比例配置</div>
      <div class="zy-box">
        <Spin size="large" fix v-if="pickupDistributionSpinShow"></Spin>
        <div class="zy-box-row">
          <div class="zy-text-bold" style="width: 400px;">角色/等级</div>
          <div class="zy-text-bold">比例</div>
          <p style="clear:both"></p>
        </div>
        <div class="zy-box-row" v-for="(item, index) in pickupDistributionRatioData" :key="index">
          <div class="zy-text-bold" style="width: 400px;">
            <p>
              {{item.roleTitle}} - {{item.roleDescription}}
            </p>
          </div>
          <Input class="zy-input" placeholder="输入返佣比例" v-model="item.commissionPercent"/>
          <p style="clear:both"></p>
        </div>
      </div>
    </div>
    <div style="margin-top: 15px;">
      <div>顶级返佣比例配置</div>
      <div class="zy-box">
        <Spin size="large" fix v-if="topDistributionSpinShow"></Spin>
        <div class="zy-box-row">
          <div class="zy-text-bold" style="width: 400px;">角色/等级</div>
          <div class="zy-text-bold">比例</div>
          <p style="clear:both"></p>
        </div>
        <div class="zy-box-row" v-for="(item, index) in topDistributionRatioData" :key="index">
          <div class="zy-text-bold" style="width: 400px;">
            <p>
              {{item.roleTitle}} - {{item.roleDescription}}
            </p>
          </div>
          <Input class="zy-input" placeholder="输入返佣比例" v-model="item.commissionPercent"/>
          <p style="clear:both"></p>
        </div>
      </div>
    </div>
    <div style="margin-top: 15px;">
      <div>分销返佣比例配置</div>
      <div class="zy-box">
        <Spin size="large" fix v-if="distributionSpinShow"></Spin>
        <div class="zy-box-row">
          <div class="zy-text-bold" style="width: 400px;">角色/等级</div>
          <div class="zy-text-bold" v-for="(item, index) in levelArr" :key="index">{{item}}级</div>
          <p style="clear:both"></p>
        </div>
        <div class="zy-box-row" v-for="(item, ratioIndex) in distributionRatioData" :key="ratioIndex">
          <div class="zy-text-bold" style="width: 400px;">
            <p>
              {{item.roleTitle}} - {{item.roleDescription}}
            </p>
          </div>
          <div v-for="(levelItem, levelIndex) in levelArr" :key="levelIndex">
            <Input class="zy-input" placeholder="输入返佣比例" v-model="item.commissionPercents[levelIndex]" />
          </div>
          <p style="clear:both"></p>
        </div>
      </div>
    </div>
    <div slot="footer">
      <Button type="default" size="large" @click="setModal = false">关闭</Button>
      <Button type="primary" size="large" @click="setDistributionRatio" :loading="setLoading">配置</Button>
    </div>
  </Modal>
</template>

<script>
import * as utils from '@/api/utils-v2'
import * as ResponseStatus from '@/api/response-status'
export default {
  name: 'DistributionRatioModal',
  props: {},
  components: {},
  data() {
    return {
      urls: {
        batchSaveUrl: '/goods-commission/admin/remove-and-batch-save/',
        listCommissionUrl: '/goods-commission/admin/all-cond',
        listRoleUrl: '/role/admin/list-distribution-roles',
        distributionLevelUrl: '/distribution/admin/distribution-level'
      },
      distributionSpinShow: false,
      topDistributionSpinShow: false,
      pickupDistributionSpinShow: false,
      setModal: false,
      setLoading: false,
      levelArr: [],
      distributionRatioData: [],
      topDistributionRatioData: [],
      pickupDistributionRatioData: [],
      title: '',
      goodsId: null,
      goodsSkuId: null,
      type: null,
      id: null,
      validFlag: true
    }
  },
  methods: {
    /**
     * 请求后台接口，获取数据
     */
    loadData(param, type, id) {
      if (param.goodsId) {
        this.goodsId = param.goodsId
      }
      if (param.goodsSkuId) {
        this.goodsSkuId = param.goodsSkuId
      }
      this.type = type
      this.id = id
      this.setModal = true
      this.topDistributionSpinShow = true
      this.distributionSpinShow = true
      // 先请求分销比例表
      utils.doPostJson(this.urls.listCommissionUrl, param, {}).then(res => {
          if (ResponseStatus.OK === res.data.code) {
            // 成功获取分销比例列表，继续获取角色
            let commissionList = res.data.data.rows
            this.loadPickupDistributionData(commissionList)
            this.loadTopDistributionData(commissionList)
            this.loadDistributionData(commissionList)
          } else {
            this.$Message.error(res.data.message)
          }
        }).catch(err => {
          console.log(err)
        })
    },
    loadPickupDistributionData(commissionList) {
      this.pickupDistributionRatioData = []
      utils.doGet('/role/admin/list-pickup-distribution-roles', {}).then(roleRes => {
        if (ResponseStatus.OK === roleRes.data.code) {
          let roleList = roleRes.data.data.rows
          let commissionLen = commissionList.length
          let roleLen = roleList.length
          for (let i = 0; i < roleLen; i++) {
            let roleItem = roleList[i]
            let ratioData = {
              roleId: roleItem.id,
              roleTitle: roleItem.title,
              roleDescription: roleItem.description,
              commissionPercent: null
            }
            for (let j = 0; j < commissionLen; j++) {
              let commissionItem = commissionList[j]
              if (this.type === 'goods' && roleItem.id === commissionItem.roleId && !commissionItem.goodsSkuId) {
                ratioData.commissionPercent = commissionItem.commissionPercent
                break
              } else if (this.type === 'goodsSku' && roleItem.id === commissionItem.roleId && commissionItem.goodsSkuId) {
                ratioData.commissionPercent = commissionItem.commissionPercent
                break
              }
            } 
            this.pickupDistributionRatioData.push(ratioData)
          }
          this.pickupDistributionSpinShow = false
        } else {
          this.pickupDistributionSpinShow = false
          this.$Message.error(roleRes.data.message)
        }
      }).catch(roleErr => {
        console.log(roleErr)
      })
    },
    loadTopDistributionData(commissionList) {
      this.topDistributionRatioData = []
      utils.doGet('/role/admin/list-top-distribution-roles', {}).then(roleRes => {
        if (ResponseStatus.OK === roleRes.data.code) {
          let roleList = roleRes.data.data.rows
          let commissionLen = commissionList.length
          let roleLen = roleList.length
          for (let i = 0; i < roleLen; i++) {
            let roleItem = roleList[i]
            let ratioData = {
              roleId: roleItem.id,
              roleTitle: roleItem.title,
              roleDescription: roleItem.description,
              commissionPercent: null
            }
            for (let j = 0; j < commissionLen; j++) {
              let commissionItem = commissionList[j]
              if (this.type === 'goods' && roleItem.id === commissionItem.roleId && !commissionItem.goodsSkuId) {
                ratioData.commissionPercent = commissionItem.commissionPercent
                break
              } else if (this.type === 'goodsSku' && roleItem.id === commissionItem.roleId && commissionItem.goodsSkuId) {
                ratioData.commissionPercent = commissionItem.commissionPercent
                break
              }
            } 
            this.topDistributionRatioData.push(ratioData)
          }
          this.topDistributionSpinShow = false
        } else {
          this.topDistributionSpinShow = false
          this.$Message.error(roleRes.data.message)
        }
      }).catch(roleErr => {
        console.log(roleErr)
      })
    },
    loadDistributionData(commissionList) {
      this.distributionRatioData = []
      utils.doGet(this.urls.listRoleUrl, {}).then(roleRes => {
        if (ResponseStatus.OK === roleRes.data.code) {
          // 成功获取角色列表，继续获取分销等级
          let roleList = roleRes.data.data.rows
          utils.doGet(this.urls.distributionLevelUrl, {}).then(levelRes => {
              if (ResponseStatus.OK === levelRes.data.code) {
                // 成功获取分销等级，开始处理数据
                let level = levelRes.data.data - 1
                let levelArr = []
                for (let i = 0; i < level; i++) {
                  levelArr.push(1 + i)
                }
                const commissionLen = commissionList.length
                const roleLen = roleList.length
                for (let i = 0; i < roleLen; i++) {
                  let roleItem = roleList[i]
                  let ratioData = {
                    roleId: roleItem.id,
                    roleTitle: roleItem.title,
                    roleDescription: roleItem.description,
                    commissionPercents: []
                  }
                  for (let j = 0; j < commissionLen; j++) {
                    let commissionItem = commissionList[j]
                    if (this.type === 'goods' && roleItem.id === commissionItem.roleId && !commissionItem.goodsSkuId) {
                      ratioData.commissionPercents.push(commissionItem.commissionPercent)
                    } else if (this.type === 'goodsSku' && roleItem.id === commissionItem.roleId && commissionItem.goodsSkuId) {
                      ratioData.commissionPercents.push(commissionItem.commissionPercent)
                    }
                  }
                  this.distributionRatioData.push(ratioData)
                }
                this.levelArr = levelArr
                // 以下循环是把暂时没有配置分销比例的角色初始化到distributionRatioData中
                for (let roleItem in roleList) {
                  for (let ratioData in this.distributionRatioData) {
                    if (roleItem.roleId === ratioData.roleId) {
                      continue
                    }
                    this.distributionRatioData.push({
                      roleId: roleItem.id,
                      roleTitle: roleItem.title,
                      roleDescription: roleItem.description,
                      commissionPercents: [null, null, null, null, null]
                    })
                  }
                }
                this.distributionSpinShow = false
              } else {
                this.distributionSpinShow = false
                this.$Message.error(levelRes.data.message)
              }
            }).catch(levelErr => {
              console.log(levelErr)
            })
        } else {
          this.$Message.error(roleRes.data.message)
        }
      }).catch(roleErr => {
        console.log(roleErr)
      })
    },
    /**
     * 设置分销比例
     */
    setDistributionRatio() {
      const topDistributionRatioData = this.setTopDistributionRatioData()
      const distributionRatioData = this.setDistributionRatioData()
      const pickupDistributionRatioData = this.setPickupDistributionRatioData()
      if (this.validFlag) {
        this.setLoading = true
        utils.doPostJson(
            this.urls.batchSaveUrl + this.type + '/' + this.id,
            topDistributionRatioData.concat(distributionRatioData).concat(pickupDistributionRatioData),
            {}
          ).then(res => {
            this.setLoading = false
            if (ResponseStatus.OK === res.data.code) {
              this.setModal = false
              this.$Message.success('佣金比例配置分配成功')
            } else {
              this.$Message.error(res.data.message)
            }
          }).catch(err => {
            console.log(err)
          })
      }
    },
    setPickupDistributionRatioData() {
      let listData = []
      const pickupDistributionRatioDataLen = this.pickupDistributionRatioData.length
      for (let i = 0; i < pickupDistributionRatioDataLen; i++) {
        let ratioData = this.pickupDistributionRatioData[i]
        const roleId = ratioData.roleId
        const ratio = parseFloat(ratioData.commissionPercent)
        if (!ratio) {
          this.validFlag = false
          this.$Message.error('请确保填写了所有顶级返佣比例')
          return
        }
        if (ratio < 0) {
          this.validFlag = false
          this.$Message.error('顶级返佣比例不能小于0')
          return
        }
        if (ratio > 100) {
          this.validFlag = false
          this.$Message.error('顶级返佣比例不能大于100')
          return
        }
        listData.push({
          goodsId: this.goodsId,
          goodsSkuId: this.goodsSkuId,
          roleId: roleId,
          distributionLevel: -1,
          commissionPercent: ratio
        })
      }
      this.validFlag = true
      return listData
    },
    setTopDistributionRatioData() {
      let listData = []
      const topDistributionRatioDataLen = this.topDistributionRatioData.length
      for (let i = 0; i < topDistributionRatioDataLen; i++) {
        let ratioData = this.topDistributionRatioData[i]
        const roleId = ratioData.roleId
        const ratio = parseFloat(ratioData.commissionPercent)
        if (!ratio) {
          this.validFlag = false
          this.$Message.error('请确保填写了所有顶级返佣比例')
          return
        }
        if (ratio < 0) {
          this.validFlag = false
          this.$Message.error('顶级返佣比例不能小于0')
          return
        }
        if (ratio > 100) {
          this.validFlag = false
          this.$Message.error('顶级返佣比例不能大于100')
          return
        }
        listData.push({
          goodsId: this.goodsId,
          goodsSkuId: this.goodsSkuId,
          roleId: roleId,
          distributionLevel: 0,
          commissionPercent: ratio
        })
      }
      this.validFlag = true
      return listData
    },
    setDistributionRatioData() {
      let listData = []
      const distributionRatioDataLen = this.distributionRatioData.length
      const levelLen = this.levelArr.length
      for (let i = 0; i < distributionRatioDataLen; i++) {
        let ratioData = this.distributionRatioData[i]
        const roleId = ratioData.roleId
        for (let j = 0; j < levelLen; j++) {
          const ratio = parseFloat(ratioData.commissionPercents[j])
          if (!ratio) {
            this.validFlag = false
            this.$Message.error('请确保填写了所有分销返佣比例')
            return
          }
          if (ratio < 0) {
            this.validFlag = false
            this.$Message.error('分销返佣比例不能小于0')
            return
          }
          if (ratio > 100) {
            this.validFlag = false
            this.$Message.error('分销返佣比例不能大于100')
            return
          }
          listData.push({
            goodsId: this.goodsId,
            goodsSkuId: this.goodsSkuId,
            roleId: roleId,
            distributionLevel: this.levelArr[j],
            commissionPercent: ratio
          })
        }
      }
      this.validFlag = true
      return listData
    }
  },
  mounted() {}
}
</script>

<style lang="less">
.zy-text-bold {
  font-weight: bold;
}
.zy-box {
  border: 1px solid #ccc;
  text-align: center;
  width: 100%;
  position: relative;
}

.zy-box-row {
  border-bottom: 1px solid #ccc;
  padding: 10px;
}
.zy-box-row:last-child {
  border-bottom: none;
}
.zy-box-row div {
  border-right: 1px solid #ccc;
  float: left;
  width: 170px;
  padding: 0px 20px 0px 5px;
}
.zy-box-row div:last-child {
  border-right: 0;
}

.zy-input input {
  text-align: center;
  height: 20px;
  outline: 0;
  border: 0;
}
.zy-input input:focus {
  outline: 0;
  border: 0;
}
</style>
